package com.vgulu.server.login.service.impl;

import com.vgulu.server.common.TConstant;
import com.vgulu.server.common.exception.VBaseException;
import com.vgulu.server.common.utils.CacheUtil;
import com.vgulu.server.common.utils.RandomStrUtil;
import com.vgulu.server.common.utils.ShareCodeUtil;
import com.vgulu.server.login.bean.AccessTokenCacheBean;
import com.vgulu.server.login.bean.LoginBean;
import com.vgulu.server.login.common.LoginCons;
import com.vgulu.server.login.repository.entity.Uid;
import com.vgulu.server.login.service.TokenService;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by wangchunsee on 16/10/4.
 */
@Service
public class TokenServiceImpl implements TokenService {

    public LoginBean setToken(Uid uid, String appId, String channel) {
        String info = LoginCons.ATokenCons.separator+ ShareCodeUtil.shareCodeBySeed(uid.getUid())
                +LoginCons.ATokenCons.separator+appId
                +LoginCons.ATokenCons.separator+channel;
        String random = RandomStrUtil.getRandLetterAndNumStr(5);
        String accessToken = random+info;
        AccessTokenCacheBean bean = new AccessTokenCacheBean();
        bean.setAccessToken(accessToken);
        bean.setUid(uid);
        String value = TConstant.gson.toJson(bean);
        boolean at = CacheUtil.set(LoginCons.ATokenCons.accessTokenPrex + info,
                value, LoginCons.ATokenCons.accessTokenTimeInSec);
        if (!at){
            throw VBaseException.ServiceException;
        }
        random = RandomStrUtil.getRandLetterAndNumStr(20);
        String refreshToken = random+info;
        at = CacheUtil.set(LoginCons.ATokenCons.refreshTokenPrex + info,
                refreshToken, LoginCons.ATokenCons.refreshTokenTimeInSec);
        if (!at){
            throw VBaseException.ServiceException;
        }
        return new LoginBean(uid,accessToken,refreshToken);
    }

    public Uid tokenVerify(String accessToken) {
        String[] arr = accessToken.split(LoginCons.ATokenCons.separator);
        if (arr.length<4){
            throw VBaseException.InvalidParam;
        }
        String channel = arr[arr.length-1];
        String appId = arr[arr.length-2];
        String uid = arr[arr.length-3];
        String info = LoginCons.ATokenCons.separator+ uid
                +LoginCons.ATokenCons.separator+appId
                +LoginCons.ATokenCons.separator+channel;
        String value = CacheUtil.get(LoginCons.ATokenCons.accessTokenPrex + info);
        if (value==null){
            throw VBaseException.InvalidParam;
        }
        AccessTokenCacheBean bean=TConstant.gson.fromJson(value,AccessTokenCacheBean.class);
        if (!accessToken.equals(bean.getAccessToken())){
            throw VBaseException.InvalidParam;
        }
        return bean.getUid();
    }

}
